<template>
  <div class="app-container">
    <el-form
      :model="sestuForm"
      ref="sestuForm"
      v-show="showSearch"
      label-width="90px"
    >
      <el-form-item label="请选择考试" prop="radio">
        <el-select
          v-model="sestuForm.examinationId"
          placeholder="请选择考试"
          @change="selectExam"
          filterable
        >
          <el-option
            v-for="item in examData"
            :key="item.value"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="请选择场次" prop="sessionId">
        <div class="nav">
          <div
            v-for="(item, index) in grouData"
            :key="index"
            :class="activeSessionIndex == index ? 'contentchange' : 'content'"
            @click="selectExamSession(item.id, index)"
          >
            {{ item.name }}
          </div>
        </div>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >批量引用</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDeleteSelect"
          >批量删除</el-button
        >
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
            >批量导入</el-button
          >
        </el-col>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getTeacherList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="examineeList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        :show-overflow-tooltip="true"
        align="center"
      />
      <el-table-column
        label="姓名"
        align="center"
        :show-overflow-tooltip="true"
        prop="teacherName"
      />
      <el-table-column
        label="性别"
        align="center"
        :show-overflow-tooltip="true"
        prop="sex"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.sex == 1"> 男 </span>
          <span v-else-if="scope.row.sex == 2"> 女 </span>
          <span v-else> 未知 </span>
        </template>
      </el-table-column>
      <el-table-column
        label="职工号"
        align="center"
        :show-overflow-tooltip="true"
        prop="teacherNo"
      />
      <el-table-column
        label="所属学院"
        align="center"
        :show-overflow-tooltip="true"
        prop="dwmc"
      />
      <el-table-column
        label="状态"
        align="center"
        :show-overflow-tooltip="true"
        prop="dqzt"
      />
      <el-table-column
        label="职称"
        align="center"
        :show-overflow-tooltip="true"
        prop="jzglbmc"
      />
      <el-table-column
        label="职位"
        align="center"
        :show-overflow-tooltip="true"
        prop="jszc"
      />
      <el-table-column
        label="操作"
        align="center"
        :show-overflow-tooltip="true"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['exam:examinee:edit']"
          >修改</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['exam:examinee:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="sestuForm.pageNum"
      :limit.sync="sestuForm.pageSize"
      @pagination="getTeacherList"
    />

    <!-- 添加或修改引入考生对话框 -->

    <el-dialog
      :title="title"
      :visible.sync="open"
      width="90%"
      append-to-body
      :before-close="handleClose"
    >
      <Teacher :showAddBtn="false" @selectTeacher="selectTeacher" />
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="
          upload.url +
          '?updateSupport=' +
          upload.updateSupport +
          '&examId=' +
          this.sestuForm.examinationId +
          '&sessionId=' +
          this.sestuForm.sessionId
        "
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <!-- <div v-show="downmsg != ''" style="margin-top: 10px"> -->
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate()"
            >下载模板</el-link
          >
          <!-- </div> -->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listExaminee,
  getExaminee,
  delExaminee,
  addExaminee,
  updateExaminee,
  exportExaminee,
  importTemplate,
} from "../../../api/exam/examinee";

import {
  addInvigilate,
  getSessionTeacher,
  deleteSessionTeacher,
} from "../../../api/exam/invigilate";

import {
  listExam,
  addExam,
  getExam,
  delExame,
  updateExam,
} from "@/api/exam/set";

import { getToken } from "@/utils/auth";

import Teacher from "../../../views/system/teacher/index.vue";

export default {
  components: { Teacher },
  name: "Examinee",
  data() {
    return {
      //传递到下一个界面的数据
      row: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      examineeIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 引入考生表格数据
      examineeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //查询考生参数
      sestuForm: {
        examinationId: "",
        sessionId: "",
        pageNum: 1,
        pageSize: 10,
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/exam/examinee/importData",
      },

      //试卷列表
      examData: [],

      //场地列表
      grouData: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        examinationId: null,
        sessionId: null,
        paperId: null,
        state: null,
        totalScore: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      //用户下载的东西
      downmsg: "",

      // 选中考试场次索引
      activeSessionIndex: 0,
    };
  },
  created() {
    this.getListexam();
  },
  methods: {
    // 获取选择考试列表
    getListexam() {
      this.loading = true;
      listExam().then((res) => {
        this.examData = res.rows;
        this.loading = false;
        this.sestuForm.examinationId = this.examData[0].id;
        console.log(this.examData);
        this.selectExam(this.sestuForm.examinationId);
      });
    },

    //查询考试详细信息，场次
    selectExam(id) {
      getExam(id).then((res) => {
        this.grouData = res.data.sessionList;
        this.sestuForm.sessionId = this.grouData[0].id;
        this.getTeacherList();
      });
    },

    /** 查询引入老师列表 */
    getTeacherList() {
      this.loading = true;
      getSessionTeacher(this.sestuForm.sessionId).then((res) => {
        this.examineeList = res.data;
        this.loading = false;
      });
    },

    // 选中某行教师
    selectTeacher(teach) {
      addInvigilate({
        userId: teach.userId,
        sessionId: this.sestuForm.sessionId,
      }).then((res) => {
        this.$message({
          showClose: true,
          duration: 1000,
          message: "导入成功",
          type: "success",
        });
      });
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.row = this.sestuForm;
      this.open = true;
      this.title = "引入监考员";
    },

    // 关闭弹出框后重新查询页面信息
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.reset();
          this.getTeacherList();
          done();
        })
        .catch((_) => {});
    },
    selectExamSession(id, index) {
      this.sestuForm.sessionId = id;
      this.activeSessionIndex = index;
      this.getTeacherList();
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "考生导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      // this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.downmsg = response.msg;
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getTeacherList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then((response) => {
        this.download(response.msg);
      });
      // importTemplate().then(response => {
      // this.download(response.msg);
      // this.download(this.downmsg);
      // this.upload.open = false;
      // this.downmsg = "";
      // });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createBy: null,
        examinationId: null,
        createTime: null,
        sessionId: null,
        userId: null,
        updateBy: null,
        paperId: null,
        updateTime: null,
        state: null,
        totalScore: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getTeacherList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.examineeIds = selection.map((item) => item.invigilateId);
      // console.log(this.examineeIds);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getExaminee(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改引入考生";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateExaminee(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getTeacherList();
            });
          } else {
            addExaminee(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getTeacherList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm(
        '是否确认删除引入职工号为"' + row.teacherNo + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return deleteSessionTeacher(row.invigilateId);
        })
        .then(() => {
          this.getTeacherList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    // 批量删除
    handleDeleteSelect(row) {
      let that = this
      
    },

    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有引入考生数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportExaminee(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
.chose {
  background-color: #e4e7ed;
}
.nav {
  display: flex;
  flex-wrap: wrap;
}
.content,
.contentchange {
  display: flex;
  border-radius: 10px;
  margin-bottom: 10px;
  // margin-right: 10px;
  // right: 5px;
  // text-align: center;
  // min-height: 28px;
  // position: relative;
  // display: block;
  padding: 8px 15px;
  // font: 16px/1.5 Arial, "微软雅黑", "Microsoft YaHei", Helvetica,
  //   "Helvetica Neue", Tahoma, Arial, sans-serif;
  // width: fit-content; //div宽度自适应文字内容
  // width: -webkit-fit-content;
  // width: -moz-fit-content;
}
.contentchange {
  margin-right: 10px;
  background-color: #409eff;
  color: #f1f1f1;
}
.content:hover {
  background-color: #f1f1f1;
}
</style>
